// src/components/AuthRoute.jsx
import { useSelector } from "react-redux";
import { Navigate, useLocation, useParams, useMatch } from "react-router-dom";
import type { RootState } from "@/store";
import  routes  from "./index.tsx";
import type { ExtendedRouteObject } from "@/types/route";

interface AuthRouteProps {
  children: React.ReactNode;
  /**
   * 路由路径，用于从路由配置中获取权限信息
   * 如果未提供，则只进行基础认证检查
   */
  routePath?: string;
  /**
   * 自定义重定向路径（权限不足时）
   */
  fallbackPath?: string;
}

/**
 * 从路由配置中查找指定路径的路由信息
 */
const findRouteByPath = (path: string, routes: ExtendedRouteObject[]): ExtendedRouteObject | null => {
  for (const route of routes) {
    if (route.path === path) {
      return route;
    }
    
    if (route.children) {
      const found = findRouteByPath(path, route.children);
      if (found) return found;
    }
  }
  return null;
};

const AuthRoute = ({ children, routePath, fallbackPath = "/" }: AuthRouteProps) => {
  const { token } = useSelector((state: RootState) => state.authSlice);
  const { userInfo, isSynced } = useSelector((state: RootState) => state.userSlice);
  const location = useLocation();
  
  // 获取当前路由的权限信息
  const currentRoute = routePath ? findRouteByPath(routePath, routes) : null;
  const requiredRoles = currentRoute?.accessRoles || [];

  // 未认证用户重定向到登录页
  if (!token) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 角色权限检查（仅在数据同步后执行）
  if (requiredRoles.length > 0) {
    // 如果数据尚未同步，显示加载状态
    if (!isSynced) {
      return (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '200px' 
        }}>
          权限验证中...
        </div>
      );
    }

    const hasRole = requiredRoles.some(role => userInfo?.userType === role);

    if (!hasRole) {
      return <Navigate to={fallbackPath} state={{ from: location }} replace />;
    }
  }

  return children;
};

export default AuthRoute;
